<template>
  <XenListPage
    title="转正申请"
    :dataList="probationList"
    :visibleFields="visibleFields"
    :filterFields="filterFields"
    :actions="actions"
    :themeConfig="themeConfig"
    :loading="loading"
    :enableAutoRefresh="false"
    :enableSilentRefresh="true"
    :silentRefreshFn="silentRefreshFn"
    searchPlaceholder="点击筛选转正申请信息"
    emptyText="暂无转正申请信息"
    emptyDesc="点击右上角添加转正申请"
    createPagePath="/subpkg-hr-syshrprobationrequestbill/create"
    detailPagePath="/subpkg-hr-syshrprobationrequestbill/details"
    editPagePath="/subpkg-hr-syshrprobationrequestbill/edit"
    permission-module="SysHrProbationRequestBill"
    @delete="handleDelete"
    @filter="handleFilter"
    @refresh="handleRefresh"
    @silent-refresh="handleSilentRefresh"
  >
    <!-- 自定义插槽图标 -->
    <template #search-icon>
      <uni-icons type="search" size="18" color="#999"></uni-icons>
    </template>
    <template #add-icon>
      <uni-icons type="plus" size="18" color="#ffffff"></uni-icons>
    </template>
    <template #loading-icon>
      <uni-icons type="spinner-cycle" size="24" color="#666"></uni-icons>
    </template>
    <template #empty-icon>
      <uni-icons type="info" size="48" color="#ccc"></uni-icons>
    </template>
    <template #action-icon-delete>
      <uni-icons type="trash" size="16" color="#FF5252"></uni-icons>
    </template>
    <template #action-icon-edit>
      <uni-icons type="compose" size="16" color="#4CAF50"></uni-icons>
    </template>
    <template #action-icon-view>
      <uni-icons type="eye" size="16" color="#7881de"></uni-icons>
    </template>
  </XenListPage>
</template>

<script lang="ts" setup>
import { ref, onMounted } from "vue";
import XenListPage from "@/layouts/XenListPage.vue";
import SysHrProbationRequestBillApi from "./api/index";
import commonApi from "@/api/common";
import { processDateRangeField } from "@/utils/dateRangeUtils";
import { formatDateTime } from "@/utils/xenUtils";
import type {
  ISysHrProbationRequestBillView,
  ISysHrProbationRequestBillQuery,
} from "./api/interface";

// 创建API实例
const api = SysHrProbationRequestBillApi();
const commonApiInstance = commonApi();

// 主题配置
const themeConfig = {
  primaryColor: "#7881de",
  secondaryColor: "#764ba2",
  gradientStart: "#667eea",
  gradientEnd: "#764ba2",
};

// 定义列表显示字段（按优先级排列）
const visibleFields = [
  {
    key: "StaffNo",
    label: "工号",
    formatter: (value: any) => value || "",
  },
  {
    key: "RegularStaffNo",
    label: "转正后工号",
    formatter: (value: any) => value || "",
  },
  {
    key: "Name",
    label: "姓名",
    formatter: (value: any) => value || "",
  },
  {
    key: "Approver",
    label: "审批人",
    formatter: (value: any) => value || "",
  },
  {
    key: "ApprovalTime",
    label: "审批时间",
    formatter: (value: any) => {
      return formatDateTime(value);
    },
  },
  {
    key: "BillCode",
    label: "单据编号",
    formatter: (value: any) => value || "",
  },
  {
    key: "BillStatus",
    label: "单据状态",
    formatter: (value: any) => {
      if (value === 0 || value === "草稿") return "草稿";
      if (value === 1 || value === "正文") return "正文";
      return value || "";
    },
  },
  {
    key: "WorkflowStatus",
    label: "工作流状态",
    type: "badge",
    formatter: (value: any) => value || "",
    badgeConfig: {
      colorMap: {
        待提交: "gray",
        提交中: "blue",
        审核中: "orange",
        已完成: "green",
        已取消: "red",
      },
      defaultColor: "gray",
      prefix: "badge-",
    },
  },
  {
    key: "Remark",
    label: "备注",
    formatter: (value: any) => value || "",
  },
  {
    key: "Phone",
    label: "手机号",
    formatter: (value: any) => value || "",
  },
  {
    key: "EntryDate",
    label: "入职日期",
    formatter: (value: any) => {
      if (!value) return "";
      const formattedDateTime = formatDateTime(value);
      return formattedDateTime ? formattedDateTime.split(" ")[0] : "";
    },
  },
  {
    key: "RegDate",
    label: "转正日期",
    formatter: (value: any) => {
      if (!value) return "";
      const formattedDateTime = formatDateTime(value);
      return formattedDateTime ? formattedDateTime.split(" ")[0] : "";
    },
  },
  {
    key: "ProbationStartDate",
    label: "试用期起始日期",
    formatter: (value: any) => {
      if (!value) return "";
      const formattedDateTime = formatDateTime(value);
      return formattedDateTime ? formattedDateTime.split(" ")[0] : "";
    },
  },
  {
    key: "ProbationEndDate",
    label: "试用期结束日期",
    formatter: (value: any) => {
      if (!value) return "";
      const formattedDateTime = formatDateTime(value);
      return formattedDateTime ? formattedDateTime.split(" ")[0] : "";
    },
  },
  {
    key: "ProbationSalary",
    label: "试用期薪资",
    formatter: (value: any) => value || "",
  },
  {
    key: "RegularSalary",
    label: "转正后薪资",
    formatter: (value: any) => value || "",
  },
  {
    key: "JobContent",
    label: "试用期工作内容",
    formatter: (value: any) => value || "",
  },
  {
    key: "JobAchievements",
    label: "试用期工作成果",
    formatter: (value: any) => value || "",
  },
  {
    key: "RegOpinion",
    label: "转正意见",
    formatter: (value: any) => value || "",
  },
  {
    key: "Remarks",
    label: "其他说明",
    formatter: (value: any) => value || "",
  },
];

// 定义搜索筛选字段
const filterFields: any[] = [
  {
    key: "name",
    label: "姓名",
    placeholder: "请输入姓名",
  },
  {
    key: "staffNo",
    label: "工号",
    placeholder: "请输入工号",
  },
  {
    key: "phone",
    label: "手机号",
    placeholder: "请输入手机号",
  },
  {
    key: "billCode",
    label: "单据编号",
    placeholder: "请输入单据编号",
  },
  {
    key: "billStatus",
    label: "单据状态",
    type: "selector",
    placeholder: "请选择单据状态",
    options: ["草稿", "正文"],
  },
  {
    key: "workflowStatus",
    label: "工作流状态",
    type: "selector",
    placeholder: "请选择工作流状态",
    options: ["待提交", "提交中", "审核中", "已完成", "已取消"],
  },
  {
    key: "approvalTime",
    label: "审批时间",
    type: "daterange",
    placeholder: "请选择审批时间范围",
  },
];

// 定义操作按钮
const actions = [
  {
    key: "delete",
    label: "删除",
    icon: "trash",
    color: "#FF5252",
    class: "delete-btn",
  },
  {
    key: "edit",
    label: "编辑",
    icon: "compose",
    color: "#4CAF50",
    class: "edit-btn",
  },
  {
    key: "view",
    label: "查看",
    icon: "eye",
    color: "#7881de",
    class: "view-btn",
  },
];

// 转正申请列表数据
const probationList = ref<ISysHrProbationRequestBillView[]>([]);

// 部门数据缓存（用于名称和ID的转换）
const departmentDataCache = ref<any[]>([]);

// 删除转正申请
const handleDelete = async (item: ISysHrProbationRequestBillView) => {
  // 调用删除API，传入ID数组
  await api.delete([item.ID!]);

  // 显示成功提示
  uni.showToast({
    title: "删除成功",
    icon: "success",
    duration: 1500,
  });
};

// 处理筛选
const handleFilter = async (filterParams: Record<string, any>) => {
  loading.value = true;

  // 构建查询参数，映射到API接口需要的字段
  const queryParams: ISysHrProbationRequestBillQuery = {
    Limit: 9999, // 一次性获取所有数据
    Page: 1,
  };

  // 根据筛选参数构建查询对象
  if (filterParams.name) {
    queryParams.Name = filterParams.name;
  }
  if (filterParams.staffNo) {
    queryParams.StaffNo = filterParams.staffNo;
  }
  if (filterParams.phone) {
    queryParams.Phone = filterParams.phone;
  }
  if (filterParams.billCode) {
    queryParams.BillCode = filterParams.billCode;
  }
  if (filterParams.billStatus) {
    queryParams.BillStatus = filterParams.billStatus;
  }
  if (filterParams.workflowStatus) {
    // 直接传递文字，不转换为数字
    queryParams.WorkflowStatus = filterParams.workflowStatus;
  }
  // 处理审批时间范围：确保结束日期包含当天的所有时间
  const approvalTimeRange = processDateRangeField(filterParams, "approvalTime");
  if (approvalTimeRange) {
    queryParams.ApprovalTime = approvalTimeRange;
  }

  const response = await api.search(queryParams);

  if (response && response.Data) {
    probationList.value = response.Data;
  } else {
    probationList.value = [];
  }

  loading.value = false;
};

// 静默刷新数据获取函数（供XenListPage组件调用）
const silentRefreshFn = async () => {
  const response = await api.search({
    Limit: 9999, // 一次性获取所有数据
    Page: 1,
  });
  return response?.Data || [];
};

// 处理静默刷新结果
const handleSilentRefresh = (newData: ISysHrProbationRequestBillView[]) => {
  probationList.value = newData;
};

// 处理刷新事件
const handleRefresh = () => {
  // 只有在首次加载或明确需要刷新时才调用fetchData
  if (probationList.value.length === 0) {
    fetchData();
  }
};

// 加载状态
const loading = ref(false);

// 获取数据
const fetchData = async () => {
  loading.value = true;

  const response = await api.search({
    Limit: 9999, // 一次性获取所有数据
    Page: 1,
  });

  if (response && response.Data) {
    probationList.value = response.Data;
  } else {
    probationList.value = [];
  }

  loading.value = false;
};

// 加载部门数据
const loadDepartmentData = async () => {
  const response = await commonApiInstance.GetParentsTree();
  if (response && Array.isArray(response)) {
    // 缓存部门数据
    departmentDataCache.value = response;
  }
};

// 页面加载
onMounted(async () => {
  await loadDepartmentData();
  fetchData();
});
</script>
